package com.cheng.system.controller;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.cheng.common.annotation.JWTIgnore;
import com.cheng.common.domain.R;
import com.cheng.system.model.User;
import com.cheng.system.service.UserService;
import com.cheng.system.service.impl.AuthUsernamePasswordImpl;
import com.cheng.system.service.impl.AuthWechatImpl;
import io.swagger.annotations.Api;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


@Api(tags = {"权限相关接口"})
@RestController
@RequestMapping("auth")
@Slf4j
public class AuthController {
    @Autowired
    UserService userService;
    @Autowired
    AuthUsernamePasswordImpl authUsernamePassword;
    @Autowired
    AuthWechatImpl authWechat;

    @JWTIgnore
    @PostMapping("login")
    @Operation(description = "登录")
//    @ApiResponse(description = "登录成功",content = @Content(schema = @Schema(implementation = SaTokenInfo.class)))
    public R<SaTokenInfo> login(@RequestBody @Validated User user) throws Throwable {
        return R.ok(authUsernamePassword.login(user));
    }

    @JWTIgnore
    @PostMapping("signUp")
    public R<SaTokenInfo> signUp(@RequestBody @Validated User user) throws Throwable {

        return R.ok(authUsernamePassword.signUp(user));
    }

    @GetMapping("wechat/login")
    @JWTIgnore
    public R<SaTokenInfo> wechatLogin(String code) throws Throwable {
        return R.ok(authWechat.login(code));
    }

    @GetMapping("isLogin")
    public R<User> isLogin() {
        if (StpUtil.isLogin()) {
            return R.ok(userService.getById((String) StpUtil.getLoginId()));
        }
        return R.ok(null);
    }

    @GetMapping("getSession")
    public R<SaSession> getSession() {
        return R.ok(StpUtil.getSession());
    }

    @GetMapping("logout")
    public R<String> logout() {
        StpUtil.logout();
        return R.ok();
    }
}
